package br.ucb.filtro;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *  To prevent user from going back to Login page if the user already logged in
 */
public class LoginPageFilter implements Filter{
   @Override
   public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException{
       HttpServletRequest request = (HttpServletRequest) servletRequest;
       HttpServletResponse response = (HttpServletResponse) servletResponse;

       if(request.getUserPrincipal() != null) {
	        String navigateString = "";
	        
	        if(request.isUserInRole("Administrator")){
	        	navigateString = "/resources/adm/AdminPrincipal.xhtml";
	        } else if(request.isUserInRole("Manager")){
	        	navigateString = "/resources/gerente/GerentePrincipal.xhtml";
	        } else if(request.isUserInRole("User")){
	        	navigateString = "/resources/user/UsuarioPrincipal.xhtml";
	        }
	        
	        response.sendRedirect(request.getContextPath() + navigateString);
       } else {
    	   filterChain.doFilter(servletRequest, servletResponse);
       }
   }

   @Override
   public void destroy(){
   }
   
   @Override
   public void init(FilterConfig filterConfig) throws ServletException{
   }
}

/*
@WebFilter("/user/*")
public class AuthorizationFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {    
        HttpServletRequest req = (HttpServletRequest) request;
        Authorization auth = (Authorization) req.getSession().getAttribute("auth");

        if (auth != null && auth.isLoggedIn()) {
            // User is logged in, so just continue request.
            chain.doFilter(request, response);
        } else {
            // User is not logged in, so redirect to index.
            HttpServletResponse res = (HttpServletResponse) response;
            res.sendRedirect(req.getContextPath() + "/index.xhtml");
        }
    }

    // You need to override init() and destroy() as well, but they can be kept empty.
}


package com.example;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebFilter("/app/*")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig config) throws ServletException {
        // If you have any <init-param> in web.xml, then you could get them
        // here by config.getInitParameter("name") and assign it as field.
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);

        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect(request.getContextPath() + "/login"); // No logged-in user found, so redirect to login page.
        } else {
            chain.doFilter(req, res); // Logged-in user found, so just continue request.
        }
    }

    @Override
    public void destroy() {
        // If you have assigned any expensive resources as field of
        // this Filter class, then you could clean/close them here.
    }

}

Compile the code and put it in the /WEB-INF/classes folder. In this particular case, the class file should end up in /WEB-INF/classes/com/example/LoginFilter.class. An IDE like Eclipse, Netbeans or IntelliJ will do it all automatically when you've created a dynamic web project.

Note that the @WebFilter annotation only works on Java EE 6 / Servlet 3.0 capable containers (Tomcat 7, Glassfish 3, JBoss AS 6, etc). If you're using an older version, then you should remove the annotation and map the filter in /WEB-INF/web.xml file as follows which does effectively the same.
<?xml version="1.0" encoding="UTF-8"?>
<web-app 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

    <filter>
        <filter-name>loginFilter</filter-name>
        <filter-class>com.example.LoginFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>loginFilter</filter-name>
        <url-pattern>/app/*</url-pattern>
    </filter-mapping>
</web-app>

Either way, it basically tells to the servletcontainer that it should do the following under the covers:
com.example.LoginFilter loginFilter = new com.example.LoginFilter();
filters.put("/app/*", loginFilter); // Add to filter mapping.

Assuming that you've deployed this webapp on http://localhost:8080/contextname, then any request which starts with the URL http://localhost:8080/contextname/app such as http://localhost:8080/contextname/app/userprofile will invoke this filter. The filter checks if the session attribute with the name "user" is present. If it is absent, then it will redirect to the login page on http://localhost:8080/contextname/login, otherwise it will just continue the request. The URL pattern /app/* is free to your choice. You can also make it /private/*, /secured/*, etc.

*/